const { incStatistics, incMultiStatistics } = require('./tool')
const { ObjectID } = require('mongodb')
const { models } = require('../model')
const { convertToObjectId } = require('../utils/db')

// 处理用户日志
async function processLog (id) {
  const doc = await models.UserLog.findById(id)
  try {
    await dispatchActivity(doc.action, doc)
    models.UserLog.markFinishedById(id)
  } catch (e) {
    console.error('ERROR: 日志处理失败 日志信息：')
    console.error(e.message)
    console.error(e.stack)
  }
}

// 分发用户活动处理
async function dispatchActivity (action, payload) {
  // @tool/like
  if (action === '@tool/like') {
    const toolId = payload.value.id
    const userId = payload.userId
    const userTookLike = await models.User.findById(userId, {
      projection: { toolLike: 1 }
    })
    if (userTookLike.toolLike) {
      const matched = userTookLike.toolLike.find(e => e.toString() === toolId.toString())
      if (matched) {
        console.error(`ERROR: 用户重复点赞 toolId:${userId} userId:${toolId}`)
      }
    }
    await incStatistics({
      id: toolId,
      statistics: {
        likeCount: 1
      }
    })
    models.User.updateById(userId, {
      $addToSet: { toolLike: ObjectID(toolId) }
    })
  } else if (action === '@tool/cancel-like') {
    const toolId = payload.value.id
    const userId = payload.userId
    await incStatistics({
      id: toolId,
      statistics: {
        likeCount: -1
      }
    })
    models.User.updateById(userId, {
      $pull: { toolLike: ObjectID(toolId) }
    })
  } else if (action === '@tool/collection') {
    // @tool/collection
    const toolId = payload.value.id
    await incStatistics({
      id: toolId,
      statistics: {
        collectionCount: 1
      }
    })
    const userId = payload.userId
    models.User.updateById(userId, {
      $addToSet: { toolCollection: ObjectID(toolId) }
    })
  } else if (action === '@tool/collections') {
    // @tool/collections
    const toolIds = payload.value.ids
    await incMultiStatistics({
      ids: toolIds,
      statistics: {
        collectionCount: 1
      }
    })
    const userId = payload.userId
    models.User.updateById(userId, {
      $addToSet: { toolCollection: { $each: convertToObjectId(toolIds) } }
    })
  } else if (action === '@tool/collectionRemove') {
    const toolId = payload.value.id
    await incStatistics({
      id: toolId,
      statistics: {
        collectionCount: -1
      }
    })
    const userId = payload.userId
    models.User.updateById(userId, {
      $pull: { toolCollection: ObjectID(toolId) }
    })
  } else if (action === '@tool/click' || (action === 'open-link' && payload.value.type === 1)) {
    // // 若平台上整理的tool被点击
    const toolId = payload.value.id
    await incStatistics({
      id: toolId,
      statistics: {
        clickCount: 1
      }
    })
  } else if (action === 'content-vote') {
    // 点赞km
    const cid = payload.value.id
    const uid = payload.userId
    models.Article.updateOne({
      _id: ObjectID(cid)
    }, {
      $inc: { 'statistics.votes': 1 }
    }, { multi: false })
    models.User.updateById(uid, {
      $addToSet: { contentVote: ObjectID(cid) }
    })
  } else if (action === 'cancel-content-vote') {
    // 取消点赞 km
    const cid = payload.value.id
    const uid = payload.userId
    models.Article.updateOne({
      _id: ObjectID(cid)
    }, {
      $inc: { 'statistics.votes': -1 }
    }, { multi: false })
    models.User.updateById(uid, {
      $pull: { contentVote: ObjectID(cid) }
    })
  } else if (action === 'show-content') {
    const cid = payload.value.id
    const uid = payload.userId
    const doc = await models.UserContent.findOne({ uid: uid, cid: cid })
    if (doc) {
      models.UserContent.updateOne({ _id: doc._id }, { $inc: { 'statistics.reads': 1 } })
    } else {
      models.UserContent.insertOne({ uid: uid, cid: cid, statistics: { reads: 1 } })
    }
  } else if (action === 'view-content') {
    const cid = payload.value.id
    const uid = payload.userId
    let duration = payload.value.duration / 1000
    if (duration > 60 * 2) duration = 60 * 2
    const doc = await models.UserContent.findOne({ uid: uid, cid: cid })
    if (doc) {
      if (doc.statistics.duration) {
        models.UserContent.updateOne({ _id: doc._id }, { $inc: { 'statistics.duration': duration } })
      } else {
        models.UserContent.updateOne({ _id: doc._id }, { $set: { 'statistics.duration': duration } })
      }
    } else {
      models.UserContent.insertOne({ uid: uid, cid: cid, statistics: { duration: duration } })
    }
  }
}

module.exports = {
  processLog,
  dispatchActivity
}
